import time

from PyQt5.QtCore import QThread
from PyQt5.QtWidgets import QWidget, QPushButton, QLineEdit, QPlainTextEdit
from PyQt5.uic import loadUi

"""
主窗口
"""


class HomeWindow:
    def __init__(self):
        # 加载ui文件创建ui对象
        self.window = loadUi('ui/home.ui')
        self.window: QWidget
        # 显示该窗口对象
        self.window.show()
        # 按钮，事件监听 绑定方法
        self.window.pushButton: QPushButton
        self.window.pushButton.clicked.connect(self.pushButton_clicked)

        # 线程对象
        self.t = None

    def pushButton_clicked(self):
        """注释部分是用来演示非线程执行任务时的故障"""
        # # 读取文本框内容
        # self.window.lineEdit: QLineEdit
        # s = self.window.lineEdit.text()
        # # 创建任务对象
        # helloWorld = HelloWorld()
        # helloWorld.name = s
        # # 输出
        # self.window.plainTextEdit: QPlainTextEdit
        # self.window.plainTextEdit.setPlainText(helloWorld.say())

        if self.t is None:
            # 读取文本框内容
            self.window.lineEdit: QLineEdit
            s = self.window.lineEdit.text()
            # 创建线程对象
            self.t = ThreadTask()
            self.t.name = s
            self.t.output_access = self.output
            # 开始线程
            self.t.start()

    def output(self, s: str):
        self.window.plainTextEdit: QPlainTextEdit
        self.window.plainTextEdit.setPlainText(s)
        # self.window.plainTextEdit.appendPlainText(s)
        # 线程结束
        self.t = None


class ThreadTask(QThread):
    def __init__(self):
        super().__init__()
        self.name = ''
        self.output_access = None

    def run(self):
        if self.output_access is not None:
            time.sleep(5)
            self.output_access('Hello world, %s' % self.name)
